package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.elasticsearch.FindCommentReplyElasticsearch;
import com.juyu.miliao.api.dao.elasticsearch.FindDynamicCommentElasticsearch;
import com.juyu.miliao.api.dao.elasticsearch.FindDynamicElasticsearch;
import com.juyu.miliao.api.dao.mysql.FindCommentReplyInfoDao;
import com.juyu.miliao.api.dao.redis.DynamicCommentInfoRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.FindCommentReplyInfo;
import com.juyu.miliao.api.domain.FindDynamicCommentInfo;
import com.juyu.miliao.api.domain.dto.FindCommentReplyInfoDTO;
import com.juyu.miliao.api.domain.vo.FindCommentReplyVO;
import com.juyu.miliao.api.domain.vo.FindDynamicVO;
import com.juyu.miliao.api.domain.vo.ResultFindCommentReplyVO;
import com.juyu.miliao.api.handler.IntegralRewardsAndPunishmentsHandler;
import com.juyu.miliao.common.constant.SpendSystemMessage;
import com.juyu.miliao.common.constant.SpendSystemMessageType;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuanqicheng
 */
@Service
public class FindCommentReplyInfoService {

    private static final Logger logger = LoggerFactory.getLogger("dynamicCommentLog");
    //回复评论
    private static final int REPLY_TYPE_BY_COMMENT = 1;
    //回复回复信息
    private static final int REPLY_TYPE_BY_REPLY = 2;
    @Autowired
    private FindDynamicCommentElasticsearch findDynamicCommentElasticsearch;

    @Autowired
    private FindDynamicElasticsearch findDynamicElasticsearch;

    @Autowired
    private FindCommentReplyElasticsearch findCommentReplyElasticsearch;
    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private FindCommentReplyInfoDao findCommentReplyInfoDao;

    @Autowired
    private CheckFindDynamicCommentAndReplyService checkFindDynamicCommentAndReplyService;

    @Autowired
    private IntegralRewardsAndPunishmentsHandler integralRewardsAndPunishmentsHandler;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;

    @Transactional(rollbackFor = Exception.class)
    public FindCommentReplyVO addCommentReply(FindCommentReplyInfoDTO commentReplyInfoDTO) throws IOException {
        FindCommentReplyVO findCommentReplyVO = new FindCommentReplyVO();
        FindDynamicCommentInfo findDynamicCommentInfo = findDynamicCommentElasticsearch
                .getFindDynamicCommentInfoByCommentId(commentReplyInfoDTO.getCommentId());

        if (findDynamicCommentInfo != null) {

            String temp = NetEaseCloudUserService.getYunTextCheck(commentReplyInfoDTO.getReplyContent());

            JSONObject json = JSONObject.parseObject(temp);

            logger.info("评论回复反垃圾响应内容：" + temp + "，评论id：" + commentReplyInfoDTO.getCommentId()
                    + ",评论回复内容：" + commentReplyInfoDTO.getReplyContent());

            String msg = json.getString("msg");
            int code = json.getIntValue("code");

            if (code == 200) {
                JSONObject result = json.getJSONObject("result");
                int action = result.getIntValue("action");
                if (action == 0) {

                    FindDynamicVO findDynamicVO = findDynamicElasticsearch
                            .getFindDynamicInfoByFindId(findDynamicCommentInfo.getFindId());
                    if (findDynamicVO != null) {
                        int isWrite = 0;
                        if (commentReplyInfoDTO.getReplyFromUserId().equals(findDynamicVO.getUserId())) {
                            isWrite = 1;
                        }

                        if (REPLY_TYPE_BY_COMMENT == commentReplyInfoDTO.getReplyType()) {
                            commentReplyInfoDTO.setReplyToUserId(findDynamicCommentInfo.getFromUserId());
                            if (!commentReplyInfoDTO.getReplyId().equals(commentReplyInfoDTO.getCommentId())) {
                                throw new ConsumeRuntimeException("replyId不正确");
                            }
                        } else if (REPLY_TYPE_BY_REPLY == commentReplyInfoDTO.getReplyType()) {
                            FindCommentReplyInfo findCommentReplyInfo = findCommentReplyInfoDao.selectById(commentReplyInfoDTO.getReplyId());
                            if (findCommentReplyInfo != null) {
                                commentReplyInfoDTO.setReplyToUserId(findCommentReplyInfo.getReplyFromUserId());
                            } else {
                                throw new ConsumeRuntimeException("replyId不正确");
                            }
                        } else {
                            throw new ConsumeRuntimeException("类型不正确");
                        }

                        FindCommentReplyInfo findCommentReplyInfo = new FindCommentReplyInfo();
                        BeanUtils.copyProperties(commentReplyInfoDTO, findCommentReplyInfo);
                        findCommentReplyInfo.setIsWriter(isWrite);
                        findCommentReplyInfo.setLikeNumber(0);

                        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        findCommentReplyInfo.setReplyDate(df.format(LocalDate.now()));
                        DateTimeFormatter dfTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        findCommentReplyInfo.setReplyTime(dfTime.format(LocalDateTime.now()));

                         int i = findCommentReplyInfoDao.addFindCommentReplyInfo(findCommentReplyInfo);
                         //返回回复评论展示所需要的所有字段
                        if(i>0){
                            BeanUtils.copyProperties(findCommentReplyInfo,findCommentReplyVO);
                            UserCacheVo replyFromUser=userInfoCache.getUserCacheInfo(findCommentReplyInfo.getReplyFromUserId());

                            String replyFromLevelPic = replyFromUser.getUserLevel().getLevelPic();

                            findCommentReplyVO.setReplyFromUserNickName(replyFromUser.getNickName());

                            findCommentReplyVO.setReplyFromUserIcon(replyFromUser.getIcon());

                            String replyFromHostPic = replyFromUser.getHostUserLevel().getHostUserGradePic();

                            findCommentReplyVO.setReplyFromEnergyGrade(replyFromUser.getUserLevel()
                                    .getEnergyGrade());

                            findCommentReplyVO.setReplyFromLevelPic(replyFromLevelPic==null?"":replyFromLevelPic);

                            findCommentReplyVO.setReplyFromHostUserGradePic(replyFromHostPic==null
                                    ? "":replyFromHostPic);

                            Integer replyFromHostUserGrade = replyFromUser.getHostUserLevel().getHostUserGrade();
                            findCommentReplyVO.setReplyFromHostUserGrade(replyFromHostUserGrade==null
                                    ?0:replyFromHostUserGrade);

                            UserCacheVo replyToUser = userInfoCache.getUserCacheInfo(findCommentReplyVO.getReplyToUserId());
                            if(findCommentReplyVO.getReplyToUserId()==1){
                                findCommentReplyVO.setReplyToUserNickName(replyToUser.getNickName());
                            }else{
                                findCommentReplyVO.setReplyToUserNickName("@ "+replyToUser.getNickName());
                            }
                            findCommentReplyVO.setReplyToUserIcon(replyToUser.getIcon());
                            String replyToLevelPic = replyToUser.getUserLevel().getLevelPic();
                            findCommentReplyVO.setReplyToEnergyGrade(replyToUser.getUserLevel()
                                    .getEnergyGrade());
                            String replyToHostPic = replyToUser.getHostUserLevel().getHostUserGradePic();
                            findCommentReplyVO.setReplyToLevelPic(replyToLevelPic==null?"":replyToLevelPic);
                            findCommentReplyVO.setReplyToHostUserGradePic(replyToHostPic==null ? "":replyToHostPic);
                            Integer replyToHostGrade = replyToUser.getHostUserLevel().getHostUserGrade();
                            findCommentReplyVO.setReplyToHostUserGrade(replyToHostGrade==null
                                    ? 0:replyToHostGrade);

                            DateTimeFormatter date = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                            String showTime = DateUtil.getShowTime(LocalDateTime.parse(findCommentReplyInfo.getReplyTime(), date));

                            findCommentReplyVO.setShowTime(showTime);

                            integralRewardsAndPunishmentsHandler
                                    .singleDynamicCommentAndReplyOver10People(findDynamicVO.getFindId(),
                                            findDynamicVO.getUserId(),findCommentReplyInfo.getReplyFromUserId());

                        }
                        findCommentReplyElasticsearch.addFindDynamicCommentInfo(findCommentReplyInfo);
                        if(findCommentReplyVO.getReplyFromUserId().longValue()
                                !=findCommentReplyVO.getReplyToUserId().longValue()){
                            sendSystemMessage(findDynamicCommentInfo.getFromUserId(),findDynamicVO);
                        }

                        checkFindDynamicCommentAndReplyService
                                .incrementDynamicCommentAndReplyNumber(findCommentReplyInfo.getReplyFromUserId());

                    }
                } else {
                    logger.info("评论回复反垃圾不通过，评论id：" + commentReplyInfoDTO.getCommentId()
                            + ",评论回复内容：" + commentReplyInfoDTO.getReplyContent());
                    throw new ConsumeRuntimeException("4113", "评论回复内容违规", HttpStatus.BAD_REQUEST);
                }
            } else {
                logger.error("评论回复反垃圾响应异常，状态码:" + code + "，状态描述：" + msg + "评论id：" + commentReplyInfoDTO.getCommentId()
                        + ",评论回复内容：" + commentReplyInfoDTO.getReplyContent());
            }

        }
        return findCommentReplyVO;
    }

    /**
     * 发送自定义评论回复消息
     * @param findDynamicVO
     */
    private void sendSystemMessage(long userId,FindDynamicVO findDynamicVO) {
        String type = SpendSystemMessageType.FIND_DYNAMIC_COMMENT_REPLY_TYPE.getCode();
        Map<String,Object> ext = new HashMap<>(1);
        ext.put("findId",findDynamicVO.getFindId());

        String template = SpendSystemMessage.FIND_DYNAMIC_COMMENT_REPLY.getMessage();
        String[] colors = SpendSystemMessage.FIND_DYNAMIC_COMMENT_REPLY.getColors();
        ext.put("template",template);

        List<String> templateList = new ArrayList<>(1);

        templateList.add(findDynamicVO.getFindTitle());

        ext.put("templateValue",templateList);
        ext.put("templateColors",colors);

        String message = SpendSystemMessage.FIND_DYNAMIC_COMMENT_REPLY.getMessage(findDynamicVO.getFindTitle());
        vestRobotMessageService.getSendMsg(userId,message,type,ext);
    }
    /**
     *
     * @param userId 请求用户id
     * @param commentId
     * @param page
     * @param pageSize
     * @return
     * @throws IOException
     */
    public ResultFindCommentReplyVO selectPage(long userId, long commentId, Integer page, Integer pageSize) throws IOException {
        ResultFindCommentReplyVO resultFindCommentReplyVO = new ResultFindCommentReplyVO();
        long total = findCommentReplyElasticsearch.getCount(commentId);
        resultFindCommentReplyVO.setTotal(total);
        if (total == 0) {
           resultFindCommentReplyVO.setReplyList(new ArrayList<>());

        }else{
            List<FindCommentReplyVO> list = findCommentReplyElasticsearch.selectPage(commentId,page,pageSize);
            resultFindCommentReplyVO.setReplyList(list);
        }
        return resultFindCommentReplyVO;
    }

    /**
     * 根据id 获取回复信息
     * @param id 回复id
     * @return
     */
    public FindCommentReplyVO getFindCommentReplyVOById(long id) throws IOException {
        return findCommentReplyElasticsearch.getFindCommentReplyVOById(id);
    }
}
